package wechat

import (
	"AccessAdmin/internal/consts"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/miniProgram"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"sync"
)

var once sync.Once
var MiniProgramInstance *miniProgram.MiniProgram

// GetMiniProgramInstance 获取小程序实例
func GetMiniProgramInstance() *miniProgram.MiniProgram {
	once.Do(func() {
		var (
			err error
			ctx = gctx.New()
		)

		AppId := g.Cfg().MustGet(ctx, "miniprogram.appid").String()
		if AppId == "" {
			AppId = consts.AppId
		}

		AppSecret := g.Cfg().MustGet(ctx, "miniprogram.secret").String()
		if AppSecret == "" {
			AppSecret = consts.AppSecret
		}

		RedisAddr := g.Cfg().MustGet(ctx, "miniprogram.redisaddr").String()
		if RedisAddr == "" {
			RedisAddr = "127.0.0.1:6379"
		}

		LogFile := g.Cfg().MustGet(ctx, "miniprogram.logfile").String()
		if LogFile == "" {
			LogFile = "./wechat.log"
		}

		MiniProgramInstance, err = miniProgram.NewMiniProgram(&miniProgram.UserConfig{
			AppID:     AppId,     // 小程序appid
			Secret:    AppSecret, // 小程序app secret
			HttpDebug: true,
			Log: miniProgram.Log{
				Level: "debug",
				File:  LogFile,
			},
			// 可选，不传默认走程序内存
			Cache: kernel.NewRedisClient(&kernel.RedisOptions{
				Addr:     RedisAddr,
				Password: "",
				DB:       7,
			}),
		})
		if err != nil {
			panic(gerror.WrapCode(gcode.CodeInvalidConfiguration, err, ""))
		}
	})
	return MiniProgramInstance
}
